<script>
const http = (page, url, {
  success = () => {
  }, data = {}, fail = () => {
  }, complete = () => {
  }, successText = '数据加载成功', failText = '数据加载失败', toLogin = true
} = {}) => {
  page.axios.post(`exam/${url}`, data).then(response => {
    if (toLogin && response.status === -1) {
      let secondsToGo = 10;
      const modal = page.$warning({
        title: '提示',
        content: `${response.msg} 页面将在 ${secondsToGo} 秒后跳转到登录。`,
        okText: '知道啦',
        onOk() {
          window.location = '/login'
        }
      });
      const interval = setInterval(() => {
        secondsToGo -= 1;
        modal.update({
          content: `${response.msg} 页面将在 ${secondsToGo} 秒后跳转到登录。`,
        });
      }, 1000);
      setTimeout(() => {
        clearInterval(interval);
        modal.destroy();
        window.location = '/login'
      }, secondsToGo * 1000);
    } else if (response.status === 0) {
      successText && page.$message.success(successText)
      success(response)
    } else {
      failText && page.$message.error(response.msg || failText)
      fail(response)
    }
    complete()
  }).catch((err) => {
    failText && page.$message.error(failText)
    fail(err);
    complete()
  })
}

const formatTime = d => {
  let date = new Date(d)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const dateToMd = date => {
  let d = new Date(date);
  return `${formatNumber(d.getMonth() + 1)}-${formatNumber(d.getDate())}`;
}

const dateToMdDay = date => {
  let d = new Date(date);
  let now = new Date()
  now = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  let dif = parseInt(d.getTime() / 24 / 3600 / 1000) - parseInt(now.getTime() / 24 / 3600 / 1000)
  if (Math.abs(dif - 1) < 3) {
    return ['前天', '昨天', '今天', '明天', '后天'][dif + 1]
  }
  return `${formatNumber(d.getMonth() + 1)}-${formatNumber(d.getDate())}`;
}

const dateToYmd = date => {
  let d = new Date(date);
  return `${d.getFullYear()}-${dateToMd(d)}`;
}

const dateToHms = date => {
  let d = new Date(date);
  return `${dateToHm(d)}:${formatNumber(d.getSeconds())}`;
}

const dateToHm = date => {
  let d = new Date(date)
  return `${d.getHours()}:${formatNumber(d.getMinutes())}`;
}

const dateToYmdHm = date => {
  let d = new Date(date)
  return `${dateToYmd(d)} ${dateToHm(d)}`
}

const sToHms = seconds =>{
  let h = seconds / 3600
  let m = seconds % 3600 /60
  let s = seconds % 60
  return `${formatNumber(parseInt(h))}:${formatNumber(parseInt(m))}:${formatNumber(parseInt(s))}`
}

const dateToYmdHms = formatTime

const arrSum = (arr, fun = x => x) => {
  let r = 0
  for (let i = 0; i < arr.length; i++) {
    r += fun(arr[i])
  }
  return r
}

const arrCount = (arr, fun = () => true) => {
  let c = 0
  for (let i = 0; i < arr.length; i++) {
    if (fun(arr[i])) {
      c++
    }
  }
  return c
}

const arrIndexOf = (arr, val, fun = x => x) => {
  for (let i = 0; i < arr.length; i++) {
    if (val === fun(arr[i])) {
      return i
    }
  }
  return -1
}

const trim = s => s.replace(/(^\s*)|(\s*$)/g, '')

const strLenLimit = (s, max, min = 1) => {
  let len = trim(s || '').length
  return len <= max && len >= min
}

const sum = arr => arrSum(arr)

const mean = arr => (arr && (arr.length > 0)) ? (sum(arr) / arr.length) : 0

const max = arr => (arr && (arr.length > 0)) ? Math.max(...arr) : 0

const min = arr => (arr && (arr.length > 0)) ? Math.min(...arr) : 0

export default {
  http,
  trim,
  formatNumber,
  dateToMd,
  dateToMdDay,
  dateToYmd,
  dateToHms,
  dateToHm,
  dateToYmdHm,
  dateToYmdHms,
  sToHms,
  arrSum,
  arrCount,
  arrIndexOf,
  strLenLimit,
  sum,
  mean,
  max,
  min
}
</script>
